import { Color } from 'https://unpkg.com/three/build/three.module.js';
import { initShaders } from '../jsm/Utils.js';
import lib from '../jsm/ThreeLib.js';
import Poly from '../jsm/Poly.js'
import Sky from '../jsm/Sky.js'
import ShapeGeo from '../jsm/ShapeGeo.js';

window.onload = function () {

    const backColor = new Color("rgba(0,0,0,1)");

    const canvas = document.getElementById("canvas");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    const gl = canvas.getContext("webgl");
    //开启颜色合成,才会有透明度的感觉
    gl.enable(gl.BLEND);
    gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);

    //初始化着色器
    initShaders(gl,
        document.querySelector("#vertexShader").innerText,
        document.querySelector("#fragmentShader").innerText);
    lib.clearCanvas(gl, new Color("rgba(0,0,0,1)"), 1);

    const arr = [
        0, 0,
        0, 600,
        600, 600,
        600, 200,
        200, 200,
        200, 400,
        300, 400,
        300, 300,
        500, 300,
        500, 500,
        100, 500,
        100, 100,
        600, 100,
        600, 0
    ];


    // const arr = [
    //     600, 600,
    //     600, 0,
    //     0, 0,
    //     0, 600,
    // ];

    const ratio = canvas.height / canvas.width;
    const rectH = 1.0;
    const rectW = rectH * ratio;
    const [halfRectW, halfRectH] = [rectW / 2, rectH / 2];


    var scaleLinearX = ScaleLinear(-halfRectW, halfRectW, 0, 600);
    var scaleLinearY = ScaleLinear(-halfRectH, halfRectH, 0, 600);

    let rect = new Poly({
        gl: gl,
        vertices: [
            halfRectW, halfRectH,
            -halfRectW, halfRectH,
            -halfRectW, -halfRectH,
            halfRectW, -halfRectH,
        ]
    });
    // rect.draw("POINTS");

    const glData = [];
    for (let i = 0; i < arr.length; i += 2) {
        glData.push(scaleLinearX(arr[i]), scaleLinearY(arr[i + 1]) * -1);
    }
    let data = new Poly({
        gl: gl,
        vertices: glData
    });
    data.draw(["POINTS", "LINE_LOOP"]);

    let shapeGeo = new ShapeGeo(glData);
    shapeGeo.getTriangle();
    shapeGeo.drawLine(gl);







    function ScaleLinear(mingl, maxgl, mincss, maxcss) {
        return function (x) {
            const curcss = (x - mincss) / (maxcss - mincss);
            return curcss * (maxgl - mingl) + mingl;
        };
    }
}